#include <wx\wx.h>
#include <wx\grid.h>
#include <wx\splitter.h>
#include "Rendering\BlockRenderers.h"
#include "Scripting\RenderScriptEngine.h"

#include <angelscript.h>

class ModuleWindow : public wxDialog
{
public:
	RenderScriptEngine *_engine;
	wxListBox *_tc1;
	wxTextCtrl *_tc3;

    ModuleWindow(RenderScriptEngine *engine, wxFrame *parent, const wxString& title, const wxPoint& pos, const wxSize& size) :
		wxDialog(parent, wxID_ANY, title, pos, size, wxCAPTION | wxCLOSE_BOX | wxRESIZE_BORDER),
		_engine(engine)
	{
		wxPanel *panel = new wxPanel(this, -1);

		wxFlexGridSizer *fgs = new wxFlexGridSizer(1, 2, 2, 2);
		_tc1 = new wxListBox(panel, -1, wxDefaultPosition, wxSize(-1, 99999));
		_tc3 = new wxTextCtrl(panel, -1, wxT(""), wxPoint(-1, -1), wxSize(-1, -1), wxTE_MULTILINE | wxTE_READONLY);

		for (auto it = engine->GetModules().begin(); it != engine->GetModules().end(); ++it)
		{
			wxString str((*it).Name);
			_tc1->InsertItems(1, &str, 0);
		}

		fgs->Add(_tc1, 1, wxEXPAND);
		fgs->Add(_tc3, 1, wxEXPAND);

		_tc1->Connect(wxEVT_COMMAND_LISTBOX_SELECTED, wxCommandEventHandler(ModuleWindow::OnListBoxSelected), NULL, this);

		fgs->AddGrowableCol(1, 1);

		panel->SetSizer(fgs);
	}

	void OnListBoxSelected(wxCommandEvent &evt)
	{
		auto &sel = _tc1->GetStringSelection();

		for (auto it = _engine->GetModules().begin(); it != _engine->GetModules().end(); ++it)
		{
			wxString str((*it).Name);

			if (sel == str)
			{
				wxString text;
				_tc3->Clear();
				text <<
					"Enabled: " << ((*it).Enabled ? "Yes" : "No") << "\r\n" <<
					"Name: " << (*it).Name << "\r\n" <<
					"Version: " << (*it).Version << "\r\n" <<
					"Friendly Name: " << (*it).Friendly << "\r\n" <<
					"Author: " << (*it).Author << "\r\n" <<
					"Hard Dependencies: " << ((*it).Dependencies.empty() ? "None" : (*it).Dependencies);

				if ((*it).Enabled)
				{
					text << "\r\n\r\n" << "Registered blocks:\r\n";

					for (auto r = _engine->Renderers->Renderers.begin(); r != _engine->Renderers->Renderers.end(); ++r)
					{
						auto &data = (*r);
					
						if (data.second.Module != (*it).Module)
							continue;

						asIScriptObject *fobj = (asIScriptObject*)data.second.Data;

						text << data.first << " : " << fobj->GetObjectType()->GetName() << "\r\n";
					}
				}
				else
				{
					text << "\r\n\r\nError Log:\r\n" << (*it).Errors;
				}

				_tc3->SetValue(text);

				break;
			}
		}
	}

private:
    wxDECLARE_EVENT_TABLE();
};

wxBEGIN_EVENT_TABLE(ModuleWindow, wxDialog)
	//EVT_MENU(wxID_EXIT, MyFrame::OnExit)
wxEND_EVENT_TABLE()